# -*- coding:utf-8 -*-
"""
网格交易,现货交易

"""
from function.interface import *
import numpy as np
from functools import reduce

class Strategy9(JyInterface):
    symbol = 'btcusdt'
    startPrice = 8888
    gridAmount = 10 # 网格数量
    ratio = 0.05
    amount = 0.001
    period = '1m'
    
    def __init__(self, **wargs):
        super(Strategy9, self).__init__(**wargs)
        self.initiating()
    
    def initiating(self):
        """初始化策略"""
        self.gridRegionLong  = [self.ratio] * self.gridAmount # 网格密度
        self.gridRegionShort = [self.ratio] * self.gridAmount
        self.gridVolumeLong  = [i * self.amount for i in range(self.gridAmount + 1)]
        self.gridVolumeShort = [i * self.amount for i in range(self.gridAmount + 1)]
        self.gridPriceLong = [reduce(lambda p, r: p*(1-r), self.gridRegionLong[:i], self.startPrice) for i in range(self.gridAmount + 1)]
        self.gridPriceShort = [reduce(lambda p, r: p*(1+r), self.gridRegionShort[:i], self.startPrice) for i in range(self.gridAmount + 1)]
        self.layer = 0 # 从0层网格开始
    
    def loop(self):
        """策略部分"""
        lastprice = self.getLastPrice(self.symbol)
        position = self.getPosition(self.symbol)   
        if self.layer >= 0 and lastprice <= self.gridPriceLong[1]: # 多头方向
            if self.layer < self.gridAmount and lastprice < self.gridPriceLong[self.layer + 1]:
                orderId = self.buy(self.symbol, lastprice, self.gridVolumeLong[self.layer + 1])
                self.layer += 1
            elif self.layer > 0 and lastprice > self.gridPriceLong[self.layer - 1] and position > 0:
                orderId = self.sell(self.symbol, lastprice, self.gridVolumeLong[self.layer])
                self.layer -= 1 # 回到上一层
        if self.layer <= 0 and lastprice >= self.gridPriceShort[1]: # 空头方向
            if -self.layer < self.gridAmount and lastprice > self.gridPriceShort[self.layer - 1] and position > 0:
                ordefId = self.sell(self.symbol, lastprice, self.gridVolumeShort[self.layer - 1])
                self.layer -= 1
            elif self.layer < 0 and lastprice < self.gridPriceShort[self.layer + 1]:
                ordefId = self.buy(self.symbol, lastprice, self.gridVolumeShort[self.layer])
                self.layer += 1          
             

if __name__ == "__main__":
    st = Strategy9(type_=1,futureOrSpot=0,appKey='e10-78937',secret='bf3-c08f5',passphrase='',transferId='M_1',grpcAddress="18.136.163.117:9309")
    st.run(st.loop)